#include "LoginJsonQuery.h"
#include <qjson/parser.h>
#include <qjson/serializer.h>
#include <QVariantMap>
#include "DbSession.h"

LoginJsonQuery::LoginJsonQuery(){
}

void LoginJsonQuery::init(const std::stringstream& query){
    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse(
            QByteArray(query.str().c_str()), &ok).toMap();
    if (!ok)
    {
        // print error in log
    }
    else
    {
        m_login = result["user"].toString();
        m_password = result["password"].toString();
    }
    m_token="Error";
    m_status="Error";
}

void LoginJsonQuery::process(){
    int userId = DbSession::getInstance().login(m_login, m_password);

    if (userId == 0)
        return;
    else
    {
        QSharedPointer<User> user = DbSession::getInstance().getUser(userId);
        m_token = user->getToken();
        m_status = "Ok";
    }
}



std::string LoginJsonQuery::outToString() const{
    if(m_status=="Error")
    {
        return "{\"status\":\"" + m_status.toStdString() + "\"}";
    }
    else
    {
        return "{\"status\":\"" + m_status.toStdString()
                + "\", \"auth_token\":\"" + m_token.toStdString() + "\"}";
    }
}

